﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace HNQXYJ.DAL
{
    /// <summary>
    /// 服务端监听程序
    /// </summary>
    public class MySocket
    {
        static Thread threadWatch = null;
        static Socket socketWatch = null;

        static bool Flage = false;
        //开始监听
        public static void btnBeginListen()
        {
            string ipAddress = "192.168.1.131";
            int port = 50001;
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress address = IPAddress.Parse(ipAddress);
            IPEndPoint endpoint = new IPEndPoint(address, port);
            socketWatch.Bind(endpoint);
            socketWatch.Listen(50);
            threadWatch = new Thread(WatchConnecting);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            Flage = true;
        }

        static Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
        static Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
        /// <summary>
        /// 监听客户端请求的方法
        /// </summary>
        static void WatchConnecting()
        {
            while (true)
            {
                try
                {
                    Socket sokConnection = socketWatch.Accept();
                    //dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection);
                    Thread thr = new Thread(RecMsg);
                    thr.IsBackground = true;
                    thr.Start(sokConnection);
                    // dictThread.Add(sokConnection.RemoteEndPoint.ToString(), thr);
                }
                catch (Exception ex)
                {

                }
            }

        }

        public static string strMsgRec = "";
        /// <summary>
        /// 服务端负责监听客户端发送来的数据的方法
        /// </summary>
        /// <param name="socketClientPara"></param>
        static void RecMsg(object socketClientPara)
        {
            Socket socketClient = socketClientPara as Socket;
            // socketClient.ReceiveTimeout
            EndPoint remoteEndPoint = socketClient.RemoteEndPoint;
            string phoneKey = "";

            while (true)
            {
                byte[] arrMsgRec = new byte[1024 * 1024];
                //设置接收客户端信息的超时时间
                //int startTickCount = Environment.TickCount;//系统开机到当前的运行时间
                // int timeOut = 30000;
                socketClient.ReceiveTimeout = 420000;//心跳间隔设置为7分钟
                int length = -1;

                try
                {

                    //length = socketClient.Receive(arrMsgRec);//接收到的数据的实际长度
                    length = socketClient.ReceiveFrom(arrMsgRec, ref remoteEndPoint);

                    //将接受到的数据转化为字符串的形式
                    strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, length);
                    char strHeader = strMsgRec[0];
                    phoneKey = strMsgRec.Substring(2, 11);

                    //处理客户端的心跳包
                    if (strHeader == 'R')
                    {
                        //套接字字典中如果没有该套接字（第一次连接或者是断开后重新连接） 就添加进去
                        if (!dict.ContainsKey(phoneKey))
                        {
                            dict.Add(phoneKey, socketClient);

                            //此处要对数据库进行处理 改变数据库中终端的状态 （在线）
                            // UpdateNewTerminalStatus(phoneKey, "在线"); //经测试此处也可用。
                        }
                        else
                        {
                            dict[phoneKey] = socketClient;
                            //
                        }
                        UpdateNewTerminalStatus(phoneKey, "在线");
                    }
                    //发送信息成功后的返回数据
                    if (strHeader == 'D')
                    {
                        //此处要往数据库的信息表中添加数据，记录数据发送是否成功。
                        // UpdateNewTerminalStatus(phoneKey, "0");
                    }
                    //断电处理
                    if (strHeader == 'P')
                    {
                        UpdateNewTerminalStatus(phoneKey, "断电");
                    }

                }
                catch (SocketException ex)//这里应该是you问题
                {
                    //收不到心跳包说明终端下线，更新数据库中的终端状态（下线）。
                    //如果是因为断电而引起的，就不再更改终端状态。
                    if (!GetStatusByPhone(phoneKey))
                    {
                        UpdateNewTerminalStatus(phoneKey, "离线");
                    }

                    dict.Remove(phoneKey);
                    //dict.Remove(socketClient.RemoteEndPoint.ToString());
                    //dictThread.Remove(socketClient.RemoteEndPoint.ToString());
                    break;
                }
                catch (Exception ex)//这里应该是you问题
                {


                    //判断终端的状态是否为“断电”
                    if (!GetStatusByPhone(phoneKey))
                    {
                        UpdateNewTerminalStatus(phoneKey, "离线");

                    }

                    dict.Remove(phoneKey);

                    break;

                }
            }

        }

        /// <summary>
        /// 向客户端发送消息
        /// </summary>
        /// <param name="list">终端列表</param>
        /// <param name="msg">要发送的信息</param>
        /// <param name="sendTimes">发送的次数</param>
        public static void btnSendMsgToAll(List<string> list, string msg, string sendTimes)
        {
            string header = "D 12345678";
            string strMsg = header + sendTimes + msg;
            byte[] arrMsg = System.Text.Encoding.GetEncoding("gb2312").GetBytes(strMsg);
            for (int i = 0; i < list.Count; i++)
            {
                if (dict.ContainsKey(list[i]))
                {
                    dict[list[i]].Send(arrMsg);
                    InsertHistoryInfo(list[i], sendTimes + msg, "成功");

                }
                else
                {
                    InsertHistoryInfo(list[i], sendTimes + msg, "失败");

                }

            }
            //foreach (Socket s in dict.Values)
            //{
            //    s.Send(arrMsg);
            //}

        }


   //     static HistoryInfoTableAdapter adapter = new HistoryInfoTableAdapter();
        /// <summary>
        /// 记录发送信息
        /// </summary>
        /// <param name="phone">终端号</param>
        /// <param name="msg">发送的信息和次数</param>
        /// <param name="flage">是否发送成功</param>
        public static void InsertHistoryInfo(string phone, string msg, string flage)
        {
            string username = Convert.ToString(HttpContext.Current.Session["name"]);
            DateTime dtime = DateTime.Now;
         //   adapter.Insert(username, phone, msg, dtime, flage);

        }



        //终止监听
        public static void btnEndListen()
        {
            //socketWatch.Shutdown(SocketShutdown.Both);
            Flage = false;
            socketWatch.Close();
            threadWatch.Abort();

        }

        /// <summary>
        /// 开启监听
        /// </summary>
        public static void StartListen()
        {
            if (Flage)
            {
                return;//监听如果已经开启就直接返回
            }
            else
            {
                btnBeginListen();//开启监听
            }
        }

        /// <summary>
        /// 更新终端数据表的状态
        /// </summary>
        /// <param name="phone">终端电话号码</param>
        /// <param name="status">终端的在线状态</param>
        public static void UpdateNewTerminalStatus(string phone, string status)
        {
           // var adapter = new TerminalAllTableAdapter();
           // adapter.TerminalAllUpdateSatusByPhone(phone, status);

        }

        /// <summary>
        /// 特地为断电处理做一个判断
        /// </summary>
        /// <param name="phone">终端号</param>
        /// <returns>一个布尔值</returns>
        public static bool GetStatusByPhone(string phone)
        {
            bool flage = false;
            //var adapter = new TerminalAllTableAdapter();
            //var dataRow = adapter.GetStatusByPhone(phone).Single();
            //if (dataRow.nvrNotes == "断电")
            //{
            //    flage = true;
            //}
            return flage;

        }


    }
}